<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Admin extends Backend
{
    public function __construct()
    {
        parent::__construct();

        $this->AdminModel = model('Admin');
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        $title = '管理员列表';

        // 获取到查询字段
        $search_field = $this->request->param('search_field', 'username');

        // 获取到查询的值
        $keyword = $this->request->param('keyword', '');

        // 条件数组
        $where = [];

        // 同时满足查询字段以及查询的值不为空
        if (!empty($search_field) && !empty($keyword)) {
            // 封装条件数组
            $where = [
                "$search_field" => $keyword
            ];
        } else {
            $keyword = '请输入相对的内容';
        }

        // 获取到管理员所有数据
        $AdminList = $this->AdminModel->where($where)->paginate(5);


        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $sun = ($AdminList->currentPage() - 1) * $AdminList->listRows();

        // 赋值
        $this->assign([
            'AdminList' => $AdminList,
            'sun' => $sun,
            'keyword' => $keyword,
            'search_field' => $search_field,
            'title' => $title
        ]);

        return $this->fetch();
    }

    // 新增
    public function add()
    {
        $title = '新增管理员';

        if ($this->request->isPost()) {
            if ($this->request->isAjax()) {
                $username = $this->request->param('username', '');

                $admin = $this->AdminModel->where('username', $username)->find();


                if ($admin) {
                    $data = [
                        'code' => 0,
                        'msg' => '该用户已经存在，请重新输入'
                    ];

                    return json($data);
                }
            }

            $data = $this->request->param();

            if ($data['newpwd'] != $data['confirmpwd']) {
                $this->error('新密码与确认密码不一致，请重新输入');
                exit;
            }

            $salt = build_ranstr();
            $AdminData = [
                'username' => $data['username'],
                'nickname' => $data['nickname'],
                'password' => md5($data['newpwd'] . $salt),
                'state' => $data['state'],
                'salt' => $salt,
              
            ];

            $res = $this->AdminModel->validate('common/Admin')->save($AdminData);

            if ($res === FALSE) {
                $this->error($this->AdminModel->getError());
                exit;
            } else {
                $this->success('新增成功', url('admin/admin/index'));
                exit;
            }
        }
        // 赋值
        $this->assign([
            'title' => $title
        ]);

        return $this->fetch();
    }

    //编辑
    public function edit()
    {
        $title = '修改管理员';

        // 地址栏上的id
        $id = $this->request->param('id', 0);
       
        $admin = $this->AdminModel->find($id);

        if (!$admin) { 
            $this->error('用户不存在，请重新选择', url('admin/admin/index'));
            exit;
        }

        // 修改资料
        if ($this->request->isPost()) {
            $nickname = $this->request->param('nickname', '');

            $newpwd = $this->request->param('newpwd', '');

            $confirmpwd = $this->request->param('confirmpwd', '');

            $state = $this->request->param('state');

            // 封装更新数据的数组
            $data = [
                'id' => $id,
                'state' => $state,
                'nickname' => $nickname,
            ];

            if (!empty($nickname)) {
                $data['nickname'] = $nickname;
            }

            if (!empty($confirmpwd) && !empty($newpwd)) {
                if ($confirmpwd != $newpwd) {
                    $this->error('新密码与确认密码不一致，请重新输入');
                    exit;
                }
                $CheckPass = md5($newpwd . $admin['salt']);

                if ($CheckPass == $admin['password']) {
                    $this->error('与原密码一致，请重新输入');
                    exit;
                }

                $salt = build_ranstr();

                $pass = md5($newpwd . $salt);

                $data['password'] = $pass;
                $data['salt'] = $salt;
            }

            $res = $this->AdminModel->isUpdate(true)->save($data);

            if ($res === FALSE) {
                $this->error($this->AdminModel->getError());
                exit;
            } else {
                if ($id == $this->LoginAdmin['id'] && !empty($confirmpwd) && !empty($data['password'])) {
                    session('LoginAdmin', null);
                    $this->success('修改成功', url('admin/index/login'));
                    exit;
                } else {
                    $this->success('修改成功', url('admin/admin/index'));
                    exit;
                }
            }
        }

        $this->assign([
            'title' => $title,
            'admin' => $admin,
            'info' => $admin

        ]);
        return $this->fetch();
    }

    // 删除
    public function delete()
    {
        if ($this->request->isAjax()) {
            // 接收删除操作的状态 0 单条 1 多条
            // $state = $this->request->param('state');

            $ids = $this->request->param('id', '');

            // $ids = !empty($ids) ? rtrim($ids,',') : '';

            $idArr = explode(',', $ids);

            $idArr = array_filter($idArr);

            // 封装返回信息的数组
            $result = [
                'code' => 0,
                'msg' => '未知信息',
            ];

            if (empty($idArr)) {
                $result['msg'] = '请选择要删除的用户';
                return json($result);
            }

            // 防止删除当前登录的用户
            if (in_array($this->LoginAdmin['id'], $idArr)) {
                $result['msg'] = '不能选中当前登录的用户，请重新选择';
                return json($result);
            }

            $res = $this->AdminModel->whereIn('id', $idArr)->delete();

            if ($res === FALSE) {
                $result['msg'] = '删除失败';
                return json($result);
            } else {
                $result['code'] = 1;
                $result['msg'] = '删除成功';
                return json($result);
            }
        }
    }

    // 单个删除
    public function del()
    {
        if ($this->request->isAjax()) {
            // 接收删除操作的状态 0 单条 1 多条
            // $state = $this->request->param('state');

            $ids = $this->request->param('id', '');

            // $ids = !empty($ids) ? rtrim($ids,',') : '';

            $idArr = explode(',', $ids);

            $idArr = array_filter($idArr);

            // 封装返回信息的数组
            $result = [
                'code' => 0,
                'msg' => '未知信息',
            ];

            if (empty($idArr)) {
                $result['msg'] = '请选择要删除的用户';
                return json($result);
            }

            // 防止删除当前登录的用户
            if (in_array($this->LoginAdmin['id'], $idArr)) {
                $result['msg'] = '不能选中当前登录的用户，请重新选择';
                return json($result);
            }

            $res = $this->AdminModel->whereIn('id', $idArr)->delete();

            if ($res === FALSE) {
                $result['msg'] = '删除失败';
                return json($result);
            } else {
                $result['code'] = 1;
                $result['msg'] = '删除成功';
                return json($result);
            }
        }
    }

    // 修改状态
    public function state()
    {
        if ($this->request->isAjax()) {
            // 接收状态
            $state = $this->request->param('state', 0);

            // 接收id
            $ids = $this->request->param('id', 0);

            // 去掉最右边的逗号
            $ids = rtrim($ids, ',');

            // 转成数组
            $idArr = explode(',', $ids);

            // halt($idArr);

            $UpData = [];

            foreach ($idArr as $item) {
                $UpData[] = [
                    'id' => $item,
                    'state' => $state
                ];
            }

            // 封装返回信息的数组
            $result = [
                'code' => 0,
                'msg' => '未知信息',
            ];

            // in_array 判断某个值是否在数组里
            if (in_array($this->LoginAdmin['id'], $idArr)) {
                $result['msg'] = '不能禁用当前登录的管理员';
                return json($result);
            }

            // 根据状态修改
            if ($state) {
                $res = $this->AdminModel->isUpdate(true)->saveAll($UpData);

                if ($res = !0) {
                    $result['msg'] = $this->AdminModel->getError();
                    return json($result);
                } else {
                    $result['code'] = 0;
                    $result['msg'] = '启用成功';
                    return json($result);
                }
            } else {

                $res = $this->AdminModel->isUpdate(true)->saveAll($UpData);


                if ($res === FALSE) {
                    $result['msg'] = $this->AdminModel->getError();
                    return json($result);
                } else {
                    $result['code'] = 1;
                    $result['msg'] = '禁用成功';
                    return json($result);
                }
            }
        }
    }
}
